<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="en">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-32x32.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="UNIX,C," />





  <link rel="alternate" href="/atom.xml" title="JOE'S BLOG" type="application/atom+xml" />






<meta name="description" content="线程 线程的一些基础知识，包括线程的创建、线程终止  线程的概念典型的UNIX进程可以看成只有一个控制线程；一个进程在某一时刻只能做一件事情。有了多个控制线程后，在程序设计时就可以把进程设计成在某一时刻做不止一件事，每个线程处理各自独立的任务。这种方法有很多好处    简化处理异步事件的代码 分解复杂的问题提高整个程序的吞吐量 使用多线程改善响应时间">
<meta name="keywords" content="UNIX,C">
<meta property="og:type" content="article">
<meta property="og:title" content="线程(十一)上">
<meta property="og:url" content="https://joewt.com/2018/06/06/pthread/index.html">
<meta property="og:site_name" content="JOE&#39;S BLOG">
<meta property="og:description" content="线程 线程的一些基础知识，包括线程的创建、线程终止  线程的概念典型的UNIX进程可以看成只有一个控制线程；一个进程在某一时刻只能做一件事情。有了多个控制线程后，在程序设计时就可以把进程设计成在某一时刻做不止一件事，每个线程处理各自独立的任务。这种方法有很多好处    简化处理异步事件的代码 分解复杂的问题提高整个程序的吞吐量 使用多线程改善响应时间">
<meta property="og:locale" content="en">
<meta property="og:image" content="https://joewt.com/img/chapter-11/figure11.2.png">
<meta property="og:image" content="https://joewt.com/img/chapter-11/figure11.3.png">
<meta property="og:image" content="https://joewt.com/img/chapter-11/figure11.5.png">
<meta property="og:updated_time" content="2018-06-06T03:09:47.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="线程(十一)上">
<meta name="twitter:description" content="线程 线程的一些基础知识，包括线程的创建、线程终止  线程的概念典型的UNIX进程可以看成只有一个控制线程；一个进程在某一时刻只能做一件事情。有了多个控制线程后，在程序设计时就可以把进程设计成在某一时刻做不止一件事，每个线程处理各自独立的任务。这种方法有很多好处    简化处理异步事件的代码 分解复杂的问题提高整个程序的吞吐量 使用多线程改善响应时间">
<meta name="twitter:image" content="https://joewt.com/img/chapter-11/figure11.2.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://joewt.com/2018/06/06/pthread/"/>





  <title>线程(十一)上 | JOE'S BLOG</title>
  








</head>



<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">JOE'S BLOG</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">好记性不如烂键盘</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-book">
          <a href="/book/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            book
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joewt.com/2018/06/06/pthread/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="JOE">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/assets/img/favicon1.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JOE'S BLOG">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">线程(十一)上</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-06-06T00:29:40+08:00">
                2018-06-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/UNIX环境高级编程/" itemprop="url" rel="index">
                    <span itemprop="name">UNIX环境高级编程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/06/06/pthread/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count gitment-comments-count" data-xid="/2018/06/06/pthread/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Words count in article&#58;</span>
                
                <span title="Words count in article">
                  
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Reading time &asymp;</span>
                
                <span title="Reading time">
                  
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="线程"><a href="#线程" class="headerlink" title="线程"></a>线程</h1><blockquote>
<p>线程的一些基础知识，包括线程的创建、线程终止</p>
</blockquote>
<h2 id="线程的概念"><a href="#线程的概念" class="headerlink" title="线程的概念"></a>线程的概念</h2><p>典型的UNIX进程可以看成只有一个控制线程；一个进程在某一时刻只能做一件事情。有了多个控制线程后，在程序设计时就可以把进程设计成在某一时刻做不止一件事，每个线程处理各自独立的任务。这种方法有很多好处  </p>
<ol>
<li>简化处理异步事件的代码</li>
<li>分解复杂的问题提高整个程序的吞吐量</li>
<li>使用多线程改善响应时间  </li>
</ol>
<a id="more"></a>
<p>每个线程都包含有表示执行环境所必须的信息。其中包括进程中标识线程的线程ID、一组寄存器值、栈、调度优先级和策略、信号屏蔽字、errno变量以及线程私有数据。  </p>
<h2 id="线程标识"><a href="#线程标识" class="headerlink" title="线程标识"></a>线程标识</h2><p>每个线程都有一个线程ID。但跟进程不一样，进程ID在整个系统中是唯一的，线程ID只有在它所属的进程上下文中才有意义。  </p>
<p>线程ID通过使用pthread_t数据类型表示，必须要使用一个函数对两个线程ID进行比较。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;pthread.h&gt;</span><br><span class="line">int pthread_equal(pthread_t tid1, pthread_t tid2);</span><br><span class="line">// 相等返回非零，不同返回0</span><br></pre></td></tr></table></figure></p>
<p>线程通过调用pthread_self函数获得自身的线程ID<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;pthread.h&gt;</span><br><span class="line">pthread_t pthread_self(void);</span><br></pre></td></tr></table></figure></p>
<h2 id="线程创建"><a href="#线程创建" class="headerlink" title="线程创建"></a>线程创建</h2><p>新增的线程可以通过调用pthread_create函数创建。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;pthread.h&gt;</span><br><span class="line">int pthread_create(pthread_t *restrict tidp, </span><br><span class="line">                   const pthread_attr_t *restrict attr,</span><br><span class="line">                   void *(*start_rtn)(void *), void *restrict arg);</span><br><span class="line">//成功返回0，失败返回错误编号</span><br></pre></td></tr></table></figure></p>
<ul>
<li>当pthread_create成功返回时，新创建线程的线程ID会被设置成tidp指向的内存单元。attr用于定制各种不同的线程属性(第12章介绍)，设置为NULL，表示创建一个具有默认属性的线程。</li>
<li>新创建的线程从start_rtn函数的地址开始执行，该函数只有一个无类型指针参数arg。如果有多个参数传递，需要把这些参数放到一个结构中，然后传递这个结构的地址进去。</li>
<li>线程创建时不能保证执行顺序  </li>
</ul>
<p>如下程序创建了一个线程，打印了进程ID、新线程的线程ID以及初始线程的线程ID。 </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">#include &quot;apue.h&quot;</span><br><span class="line">#include &lt;pthread.h&gt;</span><br><span class="line"></span><br><span class="line">pthread_t ntid;</span><br><span class="line">void printids(const char *s)&#123;</span><br><span class="line">    pid_t   pid;</span><br><span class="line">    pthread_t tid;</span><br><span class="line">    pid = getpid();</span><br><span class="line">    tid = pthread_self();</span><br><span class="line">    printf(&quot;%s pid %lu tid %lu (0x%lx)\n&quot;,s,(unsigned long)pid, (unsigned long)tid, (unsigned long)tid);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">void * thr_fn(void *arg)&#123;</span><br><span class="line">    printids(&quot;new thread:&quot;);</span><br><span class="line">    return ((void *)0);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">int main()</span><br><span class="line">&#123;</span><br><span class="line">    int err;</span><br><span class="line">    err = pthread_create(&amp;ntid, NULL, thr_fn, NULL);</span><br><span class="line">    if(err !=0 )</span><br><span class="line">        err_exit(err, &quot;can&apos;t create thread&quot;);</span><br><span class="line">    printids(&quot;main thread:&quot;);</span><br><span class="line">    sleep(1);</span><br><span class="line">    exit(0);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>运行结果如图所示<br><img src="/img/chapter-11/figure11.2.png" alt=""><br>可以看到打印出了相同的进程ID，但在mac系统上线程ID不在相同地址段范围  </p>
<h2 id="线程终止"><a href="#线程终止" class="headerlink" title="线程终止"></a>线程终止</h2><p>如果进程中的任意线程调用了exit、<code>_Exit</code>或者<code>_exit</code>，那么整个进程就会终止。<br>单个线程可以通过3种方式退出，可以在不终止整个进程的情况下，停止它的控制流。 </p>
<ol>
<li>线程可以简单的从启动例程中返回，返回值是线程的退出码。</li>
<li>线程可以被同一进程中的其他线程取消。</li>
<li>线程调用pthread_exit。</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;pthread.h&gt;</span><br><span class="line">void pthread_exit(void *rval_ptr);</span><br></pre></td></tr></table></figure>
<p>rval_ptr参数是一个无类型指针，进程中的其他线程可以通过调用pthread_join函数访问到这个指针</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;pthread.h&gt;</span><br><span class="line">int pthread_join(pthread_t thread, void **rval_ptr);</span><br><span class="line">//成功返回0，失败返回错误编号</span><br></pre></td></tr></table></figure>
<ul>
<li>调用线程将一直阻塞，直到指定的线程调用pthread_exit、从启动例程中返回或者被取消。如果线程简单地从它的启动例程返回，rval_ptr就包含返回码。如果线程被取消，由rval_ptr指定的内存单元就设置为PTHREAD_CANCELED。  </li>
<li>通过调用pthread_join自动把线程置于分离状态，这样资源就可以恢复。如果线程已经处于分离状态，pthread_join就会调用失败，返回EINVAL  </li>
</ul>
<p>如下程序展示了如何获取已经终止线程的退出码  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">#include &quot;apue.h&quot;</span><br><span class="line">#include &lt;pthread.h&gt;</span><br><span class="line"></span><br><span class="line">void *thr_fn1(void *arg)</span><br><span class="line">&#123;</span><br><span class="line">    printf(&quot;thread 1 returning\n&quot;);</span><br><span class="line">    return((void *)0);</span><br><span class="line">&#125;</span><br><span class="line">void *thr_fn2(void *arg)</span><br><span class="line">&#123;</span><br><span class="line">    printf(&quot;thread 2 exiting\n&quot;);</span><br><span class="line">    pthread_exit((void *)2);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">int main(void)</span><br><span class="line">&#123;</span><br><span class="line">    int         err;</span><br><span class="line">    pthread_t   tid1,tid2;</span><br><span class="line">    void        *tret;</span><br><span class="line">    err = pthread_create(&amp;tid1,NULL,thr_fn1,NULL);</span><br><span class="line">    if (err != 0)</span><br><span class="line">        err_exit(err, &quot;can&apos;t create thread 1&quot;);</span><br><span class="line">    err = pthread_create(&amp;tid2,NULL,thr_fn2,NULL);</span><br><span class="line">    if (err != 0)</span><br><span class="line">        err_exit(err, &quot;can&apos;t create thread 2&quot;);</span><br><span class="line">    err = pthread_join(tid1, &amp;tret);</span><br><span class="line">    if(err != 0)</span><br><span class="line">        err_exit(err, &quot;can&apos;t join with thread 1&quot;);</span><br><span class="line">    printf(&quot;thread 1 exit code %ld\n&quot;,(long)tret);</span><br><span class="line">    err = pthread_join(tid2, &amp;tret);</span><br><span class="line">    if (err != 0)</span><br><span class="line">        err_exit(err, &quot;can&apos;t join with thread 2&quot;);</span><br><span class="line">    printf(&quot;thred 2 exit code %ld\n&quot;,(long)tret);</span><br><span class="line">    exit(0);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>运行结果如下:<br><img src="/img/chapter-11/figure11.3.png" alt="">  </p>
<p>线程可以通过调用pthread_cancel函数来请求取消同一进程中的其他线程  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;pthread.h&gt;</span><br><span class="line">int pthread_cancel(pthread_t tid);</span><br><span class="line">//成功返回0，失败返回错误编号</span><br></pre></td></tr></table></figure>
<p>pthread_cancel并不等待线程终止，它仅仅提出请求  </p>
<p>线程可以安排它退出时需要调用的函数(线程清理处理程序)。一个线程可以建立多个清理处理程序。处理程序记录在栈中，他们的执行顺序与他们注册时相反。  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;pthread.h&gt;</span><br><span class="line">void pthread_cleanup_push(void (*rtn)(void *), void *arg);</span><br><span class="line">void pthread_cleanup_pop(int execute);</span><br></pre></td></tr></table></figure>
<p>当线程执行以下动作时，清理函数rtn是由pthread_cleanup_push函数调度的，调用时只有一个参数arg:  </p>
<ul>
<li>调用pthread_exit时</li>
<li>响应取消请求时</li>
<li>用非零execute参数调用pthread_cleanup_pop时  </li>
</ul>
<p>如果execute参数设置为0，清理函数将不被调用。  </p>
<p>如下程序是使用线程清理处理程序的例子  </p>
<pre><code>#include &quot;apue.h&quot;
#include &lt;pthread.h&gt;

void cleanup(void *arg)
{
    printf(&quot;cleanup: %s\n&quot;,(char *)arg);
}

void *thr_fn1(void *arg)
{
    printf(&quot;thread 1 start\n&quot;);
    pthread_cleanup_push(cleanup, &quot;thread 1 first handler&quot;);
    pthread_cleanup_push(cleanup, &quot;thread 1 second handler&quot;);
    printf(&quot;thread 1 push complete\n&quot;);
    if (arg)
        return ((void *)1);
    pthread_cleanup_pop(0);
    pthread_cleanup_pop(0);
    return ((void *)1);
}

void *thr_fn2(void *arg)
{

    printf(&quot;thread 2 start\n&quot;);
    pthread_cleanup_push(cleanup, &quot;thread 2 first handler&quot;);
    pthread_cleanup_push(cleanup, &quot;thread 2 second handler&quot;);
    printf(&quot;thread 2 push complete\n&quot;);
    if (arg)
        return ((void *)2);
    pthread_cleanup_pop(0);
    pthread_cleanup_pop(0);
    return ((void *)2);

}

int main(int argc, const char *args[])
{
    int             err;
    pthread_t       tid1,tid2;
    void            *tret;
    err = pthread_create(&amp;tid1, NULL, thr_fn1, (void*)1);
    if (err !=0 )
        err_exit(err, &quot;can&apos;t create thread 1&quot;);
    err = pthread_create(&amp;tid2, NULL, thr_fn2, (void*)1);
    if (err !=0 )
        err_exit(err, &quot;can&apos;t create thread 2&quot;);
    err = pthread_join(tid1, &amp;tret);
    if (err !=0 )
        err_exit(err, &quot;can&apos;t join with thread 1&quot;);
    printf(&quot;thread 1 exit code %ld\n&quot;, (long)tret);
    err = pthread_join(tid2, &amp;tret);
    if (err !=0 )
        err_exit(err, &quot;can&apos;t join with thread 2&quot;);
    printf(&quot;thread 2 exit code %ld\n&quot;, (long)tret);
    exit(0);
}
</code></pre><p>运行结果如下<br><img src="/img/chapter-11/figure11.5.png" alt="">  </p>
<p>mac 下会产生core文件。这是因为在mac平台上，pthread_cleanup_push是用宏实现的，而宏把某些上下文存放到栈上。当线程1在调用pthread_cleanup_push和调用pthread_cleanup_pop之间返回时，栈已被改写，而这个平台在调用清理处理程序时就用了这个被改写的上下文。在Single UNIX Specification中，函数如果在调用pthread_cleanup_push和pthread_cleanup_pop之间返回，会产生未定义行为。唯一的可移植方法是调用pthread_exit.  </p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>感谢土豪</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>Donate</span>
  </button>
  <div id="QR" style="display: none;">

    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/assets/img/alipay.png" alt="JOE Alipay"/>
        <p>Alipay</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>Post author:</strong>
    JOE
  </li>
  <li class="post-copyright-link">
    <strong>Post link:</strong>
    <a href="https://joewt.com/2018/06/06/pthread/" title="线程(十一)上">https://joewt.com/2018/06/06/pthread/</a>
  </li>
  <li class="post-copyright-license">
    <strong>Copyright Notice: </strong>
    All articles in this blog are licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> unless stating additionally.
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/UNIX/" rel="tag"># UNIX</a>
          
            <a href="/tags/C/" rel="tag"># C</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/05/06/ReadingBooks/" rel="next" title="如何真正消化一本书？">
                <i class="fa fa-chevron-left"></i> 如何真正消化一本书？
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/06/20/thinkphpMeetsSwoole/" rel="prev" title="TP5集成Swoole">
                TP5集成Swoole <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/assets/img/favicon1.png"
                alt="JOE" />
            
              <p class="site-author-name" itemprop="name">JOE</p>
              <p class="site-description motion-element" itemprop="description">爱生活，爱coding</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/yinrenxin" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:joewttx@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://learnerwn.github.io" title="Murphy" target="_blank">Murphy</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://strcpy.me" title="virusdefender" target="_blank">virusdefender</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://qulongjun.com/" title="落苏" target="_blank">落苏</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://tysb7.cn/" title="汤圆" target="_blank">汤圆</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://aconion.com" title="阿葱" target="_blank">阿葱</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://csy-anxuanxun.cn" title="csy" target="_blank">csy</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://hakana.cn" title="幻梦" target="_blank">幻梦</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.fastrun.cn" title="CrazyCodes" target="_blank">CrazyCodes</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.heanny.cn" title="Heanny" target="_blank">Heanny</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://vkkevin.xyz" title="Kevin" target="_blank">Kevin</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#线程"><span class="nav-number">1.</span> <span class="nav-text">线程</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#线程的概念"><span class="nav-number">1.1.</span> <span class="nav-text">线程的概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#线程标识"><span class="nav-number">1.2.</span> <span class="nav-text">线程标识</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#线程创建"><span class="nav-number">1.3.</span> <span class="nav-text">线程创建</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#线程终止"><span class="nav-number">1.4.</span> <span class="nav-text">线程终止</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">JOE</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>








        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  








  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://billts.site/extra_css/gitment.css">
        <script src="https://billts.site/js/gitment.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitmint({
            id: window.location.pathname, 
            owner: 'Joewt',
            repo: 'blogComment',
            
            lang: "" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
            
            oauth: {
            
            
                client_secret: 'aeba4f8f14a7d3464ef3ea9faef0d67409229e47',
            
                client_id: '12908903defa4c3347b8'
            }});
        gitment.render('gitment-container');
      }

      
      renderGitment();
      
      </script>
    







  





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  

  

  

<script src="/live2dw/lib/L2Dwidget.min.js?0c58a1486de42ac6cc1c59c7d98ae887"></script><script>L2Dwidget.init({"model":{"jsonPath":"/live2dw/assets/koharu.model.json"},"display":{"position":"left","width":75,"height":150},"mobile":{"show":true},"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/"});</script></body>
</html>
